import { Injectable } from '@nestjs/common';
import { zip } from 'compressing';
import { createWriteStream } from 'fs';
import { ConfigService } from '@nestjs/config';
import { join } from 'path';

@Injectable()
export class AlbumService {
  constructor(private readonly configService: ConfigService) {}

  upload(file) {
    console.log(file);

    // 创建一个可写流
    const filePath = join(__dirname, '../../uploads', file.originalname); // 指定文件路径
    const writeStream = createWriteStream(filePath);

    // 写入数据到文件
    // const data = '这里是要写入文件的内容';
    writeStream.write(file.buffer, () => {
      console.log('数据已写入文件');
    });

    // 关闭可写流
    writeStream.end();

    // 监听流结束事件
    writeStream.on('finish', () => {
      console.log('文件写入完成');
    });

    // 错误处理
    writeStream.on('error', (err) => {
      console.error('写入文件时发生错误:', err);
    });
  }

  async downloadAll() {
    const uploadDir = this.configService.get('file').root;
    const tarStream = new zip.Stream(); //文件压缩流
    await tarStream.addEntry(uploadDir); //压缩文件路径
    return { filename: 'hello-world.zip', tarStream };
  }
}
